#!/usr/bin/env bash

AGENT_HOME=/data/wf-deploy-agent
AGENT_NAME=agent
AGENT_IDENTITY="#AGENT_IDENTITY"

SCHEDULER_HOSTS=("#SCHEDULER_HOSTS")
for host  in ${SCHEDULER_HOSTS[*]}
do
   # shellcheck disable=SC2091
   if $(curl -m 10 --output /dev/null --silent --head --fail "$host") ; then
       echo "connected" "$host"
       DOWNLOAD_HOST=$host
       break
   else
       echo "not connected" "$host"
   fi
done

ARCH=$(uname -m)
case $ARCH in
    armv5*) ARCH="armv5";;
    armv6*) ARCH="armv6";;
    armv7*) ARCH="arm";;
    aarch64) ARCH="arm64";;
    x86) ARCH="386";;
    x86_64) ARCH="amd64";;
    i686) ARCH="386";;
    i386) ARCH="386";;
esac

OS=$(uname -s)
case $OS in
    Darwin) OS="darwin";;
    Linux) OS="linux";;
esac

# shellcheck disable=SC2107
if [ "${OS}" != "darwin" && "${OS}" != "linux" ]; then
    echo -en "${OS} is not supported.\n"
    exit 1
fi

# shellcheck disable=SC2107
if [ "${ARCH}" != "amd64" && "${ARCH}" != "arm64"  ]; then
    echo -en "${ARCH} is not supported.\n"
    exit 1
fi

AGENT_DOWNLOAD_URL=http://${DOWNLOAD_HOST}/${OS}/${ARCH}/agent.tar.gz
echo "${AGENT_DOWNLOAD_URL}"

set -u

# download agent
mkdir -p ${AGENT_HOME}
curl -L ${AGENT_DOWNLOAD_URL} -o ${AGENT_HOME}/${AGENT_NAME}.tar.gz
tar xzvf ${AGENT_HOME}/${AGENT_NAME}.tar.gz -C ${AGENT_HOME}
rm -rf ${AGENT_HOME}/${AGENT_NAME}.tar.gz
chmod +x ${AGENT_HOME}/${AGENT_NAME}

# create service
cat > /usr/lib/systemd/system/wf-agent.service << EOF
[Unit]
Description=wf-agent
After=After=network-online.target

[Service]
Type=simple
WorkingDirectory=/data/wf-deploy-agent
ExecStart=/data/wf-deploy-agent/agent
TimeoutStartSec=0
RestartSec=2
Restart=always

StartLimitInterval=60s

LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity

[Install]
WantedBy=multi-user.target
EOF

# set agent identity
echo "export WF_AGENT_IDENTITY=${AGENT_IDENTITY}" >>  /etc/environment
source /etc/environment

# start service
systemctl daemon-reload
systemctl enable wf-agent.service
systemctl start  wf-agent.service